Contents

Introduction

In this section we will discuss how to take input from files and write to files using c++.

Using cin and cout:

Using Files for reading and writing

  1. Instead of using objects of std::istream (cin) and std::ostream (cout) we can use objects of class std::ifstream (input) and std::ofstream (output)
  2. We can define our input and output objects and name them anything.
  3. This requires inclusion of #include<fstream>

Writing to file

Program 1


#include<fstream>
#include<vector>

	int main(){
	std::ofstream file;
	file.open("name_of_file.txt");
	std::vector<std::string> vec;
	vec.push_back("first line");
	vec.push_back("second line");
	vec.push_back("third line");

	for (int i=0;i<vec.size();i++)
	{
		file<<vec[i]<<std::endl;
	}
	return 0;
	}


Program 2


#include<fstream>
#include<vector>

	int main(){
	std::ofstream file;
	file.open("name_of_file.txt");
	std::vector<std::string> vec;
	vec.push_back("first line");
	vec.push_back("second line");
	vec.push_back("third line");

	for (std::string line:vec)
	{
		file<<line<<std::endl;
	}
	return 0;
	}


Program 3 (appending)

Above code will write 3 lines to the file, in order to append the file each time we open it, we can just add:
file.open("file_name.txt", std::ios::app);



#include<fstream>
#include <iostream>
#include<vector>

	int main(){
	std::ofstream file;
	file.open("Fileof_appending.txt",std::ios::app);
	if (file.is_open()){
		std::cout<<"file is open"<<std::endl;
	}
	std::vector<std::string> vec;
	vec.push_back("first line");
	vec.push_back("second line");
	vec.push_back("third line");

	for (std::string line:vec)
	{
		file<<line<<std::endl;
	}
	file.close();
	if (file.is_open()){
		std::cout<<"file is open"<<std::endl;
	}
	else{std::cout<<"file is close"<<std::endl;}
	return 0;
	}


Closing file

In C++, it's essential to close files after you're done working with them to free up system resources and ensure that any changes made to the file are properly flushed and saved. If you don't close a file explicitly, the operating system may eventually close it when your program terminates, but relying on this is not a good practice. Here's why closing files is important:

  1. *Resource Management:* Open files consume system resources, and not closing them can lead to resource leaks. The operating system may have limits on the number of open file handles a process can have, and failing to close files could result in your program reaching these limits.
  2. *Flushing Buffers:* When writing to a file, data is often buffered in memory before being physically written to the file. Closing the file ensures that any buffered data is flushed and written to the file. If you don't close the file, some data may remain in the buffer and not be saved.
  3. *Consistency:* Closing files explicitly promotes code clarity and ensures that the state of the file is consistent. If you open a file, perform operations, and then close it, you explicitly control when the file is accessed, modified, or closed.

Here's a simple example in C++ to illustrate opening, writing to, and closing a file:

#include <iostream>
#include <fstream>

int main() {
    std::ofstream outputFile("example.txt");

    if (outputFile.is_open()) {
        outputFile << "Hello, World!\n";
        // Other file operations...

        outputFile.close();  // Close the file explicitly
    } else {
        std::cerr << "Unable to open the file.\n";
    }

    return 0;
}

In this example, outputFile.close() is used to close the file explicitly after writing to it. Always ensure that you close files after you finish using them to avoid potential issues with resource management and data consistency.

Taking File Name from User

#include<iostream>
#include<fstream>
#include<vector>

	int main(){

	std::string filename;
	std::cout<<"enter file name"<<std::endl;
	std::cin>>filename;
	std::ofstream file(filename, std::ios::app);
	
	std::vector<std::string> vec;
	vec.push_back("first line");
	vec.push_back("second line");
	vec.push_back("third line");

	for (std::string line:vec)
	{
		file<<line<<std::endl;
	}
	file.close();
	if (file.is_open()){
		std::cout<<"file is open"<<std::endl;
	}
	else{std::cout<<"file is close"<<std::endl;}
	
return 0;
}


Reading from file

  1. cin is object of class std::istream, similerly we need to create an object of class std::ifstream, which we can do so by:

std::ifstream fin;, we can name it anyting, (fin, or input, or fileinput).

Program (reding by char, word, lines)


#include<fstream>
#include <string>
#include <vector>
#include<iostream>
using std::endl;
using std::cout;
using std::cin;
using std::vector;
using std::string;
int main(){

std::string filename;
cout<<"enter file name to read it"<<endl;
cin>>filename;

std::ifstream fin(filename);

int choice;
cout<<"enter 0 to read character by character or 1 to read word by word, or 2 to read line by line"<<endl;
cin>>choice;

if (choice==0)
{
	vector<char> charArray;
	char input;

	while(fin>>input)
	{
		charArray.push_back(input);
	}

	for(char input:charArray)
	{
		cout<<input<<endl;
	}
	// or you can simply use fin.get() to get first letter of line
	/* char ch; */

    /* // Read characters from the file using get() */
    /* while (fin.get(ch)) { */
        /* // Process the character as needed */
        /* std::cout << "Read character: " << ch << std::endl; */
    /* } */

    fin.close();	
	
}

else if(choice==1)
{
	string input;
	vector<string> wordArray;
	while(fin>>input)
	{
		wordArray.push_back(input);
		//cout<<input<<endl; // we can directly print it here, rather than storing to a vector and printing it.

	}
	for(string letter : wordArray)
	{
		cout<<letter<<endl;
	}
fin.close();

}
else if(choice==2)
{
	string line;
	vector<string> lineArray;
	while(std::getline(fin,line))
	{
		lineArray.push_back(line);
	}
	for(std::string line:lineArray)
	{
		cout<<line<<endl;
	}

fin.close();
}
return 0;
}